/**
 * axios 二次封装
 */
import axios from 'axios';
import config from './../config';
import { ElMessage } from 'element-plus';
import router from './../router';
import storage from './../utils/storage';

const service = axios.create({
  baseURL: config.baseApi,
  timeout: 1000 * 8,
});

// 请求 拦截器
service.interceptors.request.use(
  (request) => {
    const headers = request.headers;
    // 添加 token
    let { token } = storage.getItem('userInfo') || {};
    headers.Authorization = `Bearer ${token}`;
    return request;
  },
  (err) => {
    console.log(`error: ${err}`);
    return Promise.reject(err);
  }
);

// 响应 拦截器
service.interceptors.response.use(
  (response) => {
    if (config.env !== 'prod') {
      console.log(response.config.method, response.config.url, response.data);
    }
    let { code, data, msg } = response.data;
    if (code === config.successCode) {
      return data;
    } else if (code === config.tokenInvalidCode) {
      msg = msg ? msg : config.tokenInvalidMsg;
      ElMessage.error(msg);
      setTimeout(() => {
        router.push('/login');
      }, 1500);
      return Promise.reject(msg);
    } else {
      msg = msg ? msg : config.errorMsg;
      ElMessage.error(msg);
      return Promise.reject(msg);
    }
  },
  (err) => {
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          console.log('请求错误');
          break;
        case 401:
          console.log('未授权访问');
          break;
        default:
          console.log('其他错误信息');
      }
    }
    return Promise.reject(err);
  }
);

/**
 * 请求核心函数
 * @param {*} options 请求配置
 */
function request(options) {
  options.method = options.method || 'get';
  // get 请求参数和其他请求参数处理
  if (options.method.toLowerCase() === 'get') {
    options.params = options.data;
  }
  // 请求中配置了mock 优先级比全局配置要高
  let isMock = config.mock;
  if (typeof options.mock != 'undefined') {
    isMock = options.mock;
  }
  if (config.env === 'prod') {
    // 生产环境不考虑 mock
    service.defaults.baseURL = config.baseApi;
  } else {
    service.defaults.baseURL = isMock ? config.mockApi : config.baseApi;
  }

  return service(options);
}

// 增强 request.get(url, data, options)
// request.get('/login', { username: 'zhangsan' }, { token: true })
['get', 'post', 'delete', 'put', 'patch'].forEach((type) => {
  request[type] = (url, data, options) => {
    return request({ url, data, method: type, ...options });
  };
});

export default request;
